package com.atguigu.gmall.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.feign.order.OrderFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.pay.properties.AliPayProperties;
import com.atguigu.gmall.pay.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Autowired
    private OrderFeignClient orderFeignClient ;

    @Autowired
    private AliPayProperties aliPayProperties ;

    @Autowired
    private AlipayClient alipayClient ;

    @Override
    public String pay(Long orderId) {

        // 创建一个封装请求参数的对象
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest() ;
        alipayTradePagePayRequest.setNotifyUrl(aliPayProperties.getNotifyUrl());
        alipayTradePagePayRequest.setReturnUrl(aliPayProperties.getReturnUrl());

        // 构建业务数据
        Result<OrderInfo> infoResult = orderFeignClient.findOrderInfo(orderId);
        OrderInfo orderInfo = infoResult.getData();
        Map<String , Object> params = new HashMap<>() ;
        params.put("out_trade_no" , orderInfo.getOutTradeNo()) ;
        params.put("total_amount" , orderInfo.getTotalAmount()) ;
        params.put("subject" , orderInfo.getTradeBody()) ;
        params.put("product_code" , "FAST_INSTANT_TRADE_PAY") ;

        Date expireTime = orderInfo.getExpireTime();     // 获取订单的超时时间

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
        String expireTimeStr = simpleDateFormat.format(expireTime);
        params.put("time_expire" , expireTimeStr) ;

        String parmasJSON = JSON.toJSONString(params);
        alipayTradePagePayRequest.setBizContent(parmasJSON);

        // 发送请求获取响应结果
        String result = null;

        try {
            result = alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
            log.info("result: {}" , result);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        // 返回
        return result;
    }

}
